package com.xuantu.learn.test;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.core.joran.spi.JoranException;
import org.junit.runners.model.InitializationError;
import org.slf4j.impl.StaticLoggerBinder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;

import java.io.FileNotFoundException;
import java.net.URL;

/** 在单元测试时加载logback日志框架
 * User: ping
 * Date: 15-1-6
 * Time: 下午4:28
 */
public class JUnit4Runner extends SpringJUnit4ClassRunner {

    static {
        String resolvedLocation = SystemPropertyUtils.resolvePlaceholders("classpath:logback.xml");
        URL url = null;
        try {
            url = ResourceUtils.getURL(resolvedLocation);
            LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();

            loggerContext.reset();

            new ContextInitializer(loggerContext).configureByResource(url);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JoranException e) {
            e.printStackTrace();
        }
    }

    public JUnit4Runner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }
}
